package com.extension.company.common.widget.popuwindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.extension.company.admin.R;
import com.extension.company.common.utils.StringUtils;
import com.extension.company.model.db.ReadAreaDataBase;
import com.extension.company.model.entity.AreaData;
import com.extension.company.view.adapter.OnRecyclerViewClickListener;
import com.extension.company.view.adapter.PwAddressListAddAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 添加收货地址的popwindow
 */
public class PwAddressListAddPopWindow extends PopupWindow implements View.OnClickListener {
	private Activity context;

	private RecyclerView mRecyclerView;
	private TabLayout tablayout;
	private TextView tv_title;
	private List<AreaData> list;
	private PwAddressListAddAdapter adapter;

	private OnPwAddressListAddListener mOnPwAddressListAddListener;
	private ReadAreaDataBase readAreaDataBase;

	private String provice, city, county;
	private String proviceId, cityId, countyId;
	private List<String> ids;
	/**
	 * 点击后的类型：index =0 省级 index=1 市级 index=2 乡镇
	 */
	private int index = 0;

	public PwAddressListAddPopWindow(Activity context) {
		super(context);
		this.context = context;
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View mMenuView = inflater.inflate(R.layout.pw_addresslistadd, null);

		initView(mMenuView);

		initData();

		setListener();

		//设置SelectPicPopupWindow的View
		this.setContentView(mMenuView);
		//设置SelectPicPopupWindow弹出窗体的宽
		this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
		//设置SelectPicPopupWindow弹出窗体的高
		this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
		//设置SelectPicPopupWindow弹出窗体可点�?
		this.setFocusable(true);
		//设置SelectPicPopupWindow弹出窗体动画效果
		//this.setAnimationStyle(R.style.AnimBottom);
		//实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(0x00000000);
		//设置SelectPicPopupWindow弹出窗体的背�?
		this.setBackgroundDrawable(dw);
		//设置动画
		setAnimationStyle(R.style.popwin_anim_style);
		//mMenuView添加OnTouchListener监听判断获取触屏位置如果在�?�择框外面则�?毁弹出框
		//点击外边框关�?
		setOutsideTouchable(true);
		mMenuView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int top = mMenuView.findViewById(R.id.layout_main).getTop();
				if (event.getAction() == MotionEvent.ACTION_UP) {
					int y = (int) event.getY();
					if (y < top) {
						PwAddressListAddPopWindow.this.dismiss();
					}
				}
				return true;
			}
		});
	}

	//初始化view
	private void initView(View mMenuView) {
		tv_title = mMenuView.findViewById(R.id.tv_title);
		tablayout = mMenuView.findViewById(R.id.tablayout);
		tablayout.addTab(tablayout.newTab().setText("请选择"), true); // 省
		tablayout.addTab(tablayout.newTab().setText("请选择"), false); // 市
		tablayout.addTab(tablayout.newTab().setText("请选择"), false); //区

		mRecyclerView = mMenuView.findViewById(R.id.mRecyclerView);             // 展示区
		LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
		linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		mRecyclerView.setLayoutManager(linearLayoutManager);
	}

	/**
	 * 初始化数据库数据
	 */
	private void initData() {
		readAreaDataBase = new ReadAreaDataBase(context); // 打开数据库
		list = readAreaDataBase.query("0");       // 获取34个省
		ids = new ArrayList<String>();
		ids.add("0");
		ids.add("0");
		ids.add("0");
		adapter = new PwAddressListAddAdapter(context, list);  // 将34个省都填充到recycleview中去
		mRecyclerView.setAdapter(adapter);
	}

	private void setListener() {
		this.setOnDismissListener(new PopupWindow.OnDismissListener() { // popwindow的点击事件，popwindow隐藏的时候，设置背景颜色
			@Override
			public void onDismiss() {
				backgroundAlpha(1f);
			}
		});
		//禁止tab点击
		enableTabView(false);
		tablayout_OnTabSelectedListener();
		adapter.setOnClickListener(new OnRecyclerViewClickListener() {  // recycleview的点击事件
			@Override
			public void onItemClick(View view, int position) {
				if (index == 0) {
					provice = list.get(position).getName();
					proviceId = list.get(position).getId();
				} else if (index == 1) {
					city = list.get(position).getName();
					cityId = list.get(position).getId();
				} else if (index == 2) {
					county = list.get(position).getName();
					countyId = list.get(position).getId();
				}
				tablayout.getTabAt(index).setText(list.get(position).getName()); // 跟新tablayout的item的名称
				enableTabView(index, true);   // tablayout可点击
				index++;
				if (index > 2) {  // 若选择乡镇后，则重置相关参数
					index = 0;
					list = readAreaDataBase.query("0");
					adapter.setContent(list);
					tablayout.getTabAt(0).setText("请选择");
					tablayout.getTabAt(1).setText("请选择");
					tablayout.getTabAt(2).setText("请选择");
					//禁止tab点击
					enableTabView(false);
					if (mOnPwAddressListAddListener != null) {
						mOnPwAddressListAddListener.pwAddressListAdd(provice, city, county); // 回调选中的城市
						mOnPwAddressListAddListener.pwAddressListAddId(proviceId, cityId, countyId);
					}
					dismiss();
				} else {     // 点击省、市 的item
					ids.set(index, list.get(position).getId());  // 获取相应的省、市的 id存到ids， 0 位置是省的id, 1 位置 市的位置
				}
				tablayout.getTabAt(index).select();
			}

			@Override
			public void onItemLongClick(View view, int position) {

			}
		});
	}

	/**
	 * tab 省、市、区 的点击事件
	 */
	private void tablayout_OnTabSelectedListener() {
		tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
			@Override
			public void onTabSelected(TabLayout.Tab tab) {
				index = tab.getPosition();
				if (index == 0) {   // 如果点击省tab ，则，市、区都默认设置不可点击
					tablayout.getTabAt(1).setText("请选择");  // 重置市的tab的值
					tablayout.getTabAt(2).setText("请选择");   // 重置tab的值
					enableTabView(1, false);  // 市tab不可点击
					enableTabView(2, false);   // 区不可点击
				} else if (index == 1) {  // 点击了市tab
					tablayout.getTabAt(2).setText("请选择");  // 重置区的tab值
					enableTabView(2, false);   // 设置区不可点击
				}
				list = readAreaDataBase.query(ids.get(index));  // 根据点击tablayout的0，1,2位置（省，市 区），查询数据库，更新recycleView
				adapter.setContent(list);  // 将查询到的数据展示
			}

			@Override
			public void onTabUnselected(TabLayout.Tab tab) {

			}

			@Override
			public void onTabReselected(TabLayout.Tab tab) {

			}
		});
	}

	/**
	 * 设置tablayout 的tab item 是否可以点击
	 *
	 * @param enable 是否可点击
	 */
	private void enableTabView(boolean enable) {
		LinearLayout tabStrip = (LinearLayout) tablayout.getChildAt(0);
		for (int i = 0; i < tabStrip.getChildCount(); i++) {
			View tabView = tabStrip.getChildAt(i);
			if (tabView != null) {
				tabView.setClickable(enable);
			}
		}
	}

	/**
	 * 设置tablayout 的tab item 是否可以点击
	 *
	 * @param position 需要点击的位置
	 * @param enable   是否需要点击
	 */
	private void enableTabView(int position, boolean enable) {
		LinearLayout tabStrip = (LinearLayout) tablayout.getChildAt(0);
		View tabView = tabStrip.getChildAt(position);
		if (tabView != null) {
			tabView.setClickable(enable);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

			default:
				break;
		}
	}

	/**
	 * 接口：回调地址名和地址的id
	 */
	public interface OnPwAddressListAddListener {
		void pwAddressListAdd(String provice, String city, String county);

		void pwAddressListAddId(String proviceId, String cityId, String countyId);
	}

	/**
	 * recycleView 设置点击的方法
	 *
	 * @param mOnPwAddressListAddListener
	 */
	public void setOnPwAddressListAddListener(OnPwAddressListAddListener mOnPwAddressListAddListener) {
		this.mOnPwAddressListAddListener = mOnPwAddressListAddListener;
	}

	public void setTitle(String title) {
		tv_title.setText(title);
	}

	/**
	 * 显示popupWindow
	 *
	 * @param parent
	 */
	public void showPopupWindow(View parent) {
		if (!this.isShowing()) {
			// 以下拉方式显示popupwindow
			this.showAsDropDown(parent, parent.getLayoutParams().width / 2, 20);
		} else {
			this.dismiss();
		}
	}

	/**
	 * 显示
	 */
	public void show() {
		if (!this.isShowing()) {
			if (StringUtils.isEmpty(list)) {
				list = readAreaDataBase.query("0");
				adapter.setContent(list);
			}
			hideSoftInputView();
			this.showAtLocation(((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0), Gravity.CENTER, 0, 0);
			backgroundAlpha(0.7f);
		} else {
			this.dismiss();
		}
	}

	private void backgroundAlpha(float bgAlpha) {
		if (bgAlpha == 1) {
			//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
			context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		} else {
			//此行代码主要是解决在华为手机上半透明效果无效的bug
			context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		}
		WindowManager.LayoutParams lp = context.getWindow().getAttributes();
		lp.alpha = bgAlpha; // 0.0~1.0
		context.getWindow().setAttributes(lp); //act 是上下文context
	}

	//强制隐藏软盘
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE));
		if (context.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (context.getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
}
